package com.atguigu.meinian.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.meinian.constant.MessageConstant;
import com.atguigu.meinian.service.MemberService;
import com.atguigu.meinian.service.OrderSerivce;
import com.atguigu.meinian.service.ReportService;
import com.atguigu.meinian.service.SetmealService;
import com.atguigu.meinian.vo.R;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zbystart
 * @create 2021-06-28 14:11
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private OrderSerivce orderSerivce;

    @Reference
    private ReportService reportService;

    @GetMapping("/getMemberReport")
    public R getMemberReport() {
        ArrayList<String> months = new ArrayList<>();
        // 获取前12个月的每一个的会员注册数量
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MONTH,-12);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        for (int i = 1; i<=12; i++) {
            String format = dateFormat.format(instance.getTime());
            months.add(format);
            instance.add(Calendar.MONTH,1);
//            System.out.println(format);
        }

        List<Integer> counts = memberService.selectMemberRegisterCountByMonth(months);

        HashMap<String, Object> map = new HashMap<>();
        map.put("months",months);
        map.put("memberCount",counts);
        return R.ok(MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    @GetMapping("/getSetmealReport")
    public R getSetmealReport() {
        // 获取前6个的套餐预约数量
        Map<String,Object> data = orderSerivce.selectHotSetmealOrderCount(6);
        return R.ok(MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,data);
    }

    @GetMapping("/getBusinessReportData")
    public R getBusinessReportData() {
        Map<String,Object> data = reportService.getBusinessReportData();
        return R.ok(MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
    }

    /**
     *                 todayNewMember :0, // 新增会员数
     *                 totalMember :0,// 总会员数
     *                 thisWeekNewMember :0,// 本周新增会员数
     *                 thisMonthNewMember :0,// 本月新增会员数
     *                 todayOrderNumber :0,// 今日预约数
     *                 todayVisitsNumber :0,// 今日出游数
     *                 thisWeekOrderNumber :0,// 本周预约数
     *                 thisWeekVisitsNumber :0,// 本周出游数
     *                 thisMonthOrderNumber :0,// 本月预约数
     *                 thisMonthVisitsNumber :0,// 本月出游数
     *                                     {name:'海南7天6晚游套餐',setmeal_count:200,proportion:0.222},
     *                     {name:'深圳3天2晚游套餐',setmeal_count:200,proportion:0.222}
     * @param servletContext
     * @param response
     * @return
     */
    @GetMapping("/exportBusinessReport")
    public R exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream out = null;
        XSSFWorkbook sheets = null;
        try {
            Map<String, Object> data = reportService.getBusinessReportData();

            String path = request.getSession().getServletContext().getRealPath("static") + File.separator + "template" + File.separator + "report_template.xlsx";

            sheets = new XSSFWorkbook(new FileInputStream(path));

            XSSFSheet sheetAt = sheets.getSheetAt(0);

            XSSFRow row = sheetAt.getRow(2);
            row.getCell(5).setCellValue(data.get("reportDate") + "");

            row = sheetAt.getRow(4);
            row.getCell(5).setCellValue(data.get("todayNewMember") + "");
            row.getCell(7).setCellValue(data.get("totalMember") + "");

            row = sheetAt.getRow(5);
            row.getCell(5).setCellValue(data.get("thisWeekNewMember") + "");
            row.getCell(7).setCellValue(data.get("thisMonthNewMember") + "");

            row = sheetAt.getRow(7);
            row.getCell(5).setCellValue(data.get("todayOrderNumber") + "");
            row.getCell(7).setCellValue(data.get("todayVisitsNumber") + "");

            row = sheetAt.getRow(8);
            row.getCell(5).setCellValue(data.get("thisWeekOrderNumber") + "");
            row.getCell(7).setCellValue(data.get("thisWeekVisitsNumber") + "");

            row = sheetAt.getRow(9);
            row.getCell(5).setCellValue(data.get("thisMonthOrderNumber") + "");
            row.getCell(7).setCellValue(data.get("thisMonthVisitsNumber") + "");


            List<Map<String,Object>> list = (List<Map<String, Object>>) data.get("hotSetmeal");
            int rowCount = 12;
            for (int i = 0; i<list.size(); i++) {
                Map<String, Object> map = list.get(i);
                row = sheetAt.getRow(rowCount);
                if (row == null) {
                    row = sheetAt.createRow(rowCount);
                }
                rowCount++;
                XSSFCell cell = row.getCell(4);
                if (cell == null) {
                    cell = row.createCell(4);
                }
                cell.setCellValue(map.get("name") + "");

                cell = row.getCell(5);
                if (cell == null) {
                    cell = row.createCell(5);
                }
                cell.setCellValue(map.get("setmeal_count") + "");

                cell = row.getCell(6);
                if (cell == null) {
                    cell = row.createCell(6);
                }
                cell.setCellValue(map.get("proportion") + "");
            }

            //通过输出流进行文件下载
            out = response.getOutputStream();
            // 下载的数据类型（excel类型）
            response.setContentType("application/vnd.ms-excel");
            // 设置下载形式(通过附件的形式下载)
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            sheets.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();

                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (sheets != null) {
                try {
                    sheets.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

        return null;
    }

}
